import { config } from "@/config";
import api from "@/api";
import { PrefixType, VagueOject } from "@/types/common";
import serve from "@/serve/_";
import { push } from "@/router";
import moment from 'moment'
import { Menu } from "@/types/response/Menu";
const modules = import.meta.glob('@/views/admin/**/*.vue')


export const setItem = (key: string, value: any): void => {
    localStorage.setItem(
        key,
        value.constructor == Object || value.constructor == Array
            ? JSON.stringify(value)
            : value
    )
}

export const getItem = (key: string): [] | {} | any => {
    if (localStorage.getItem(key) == null) {
        return false
    } else {
        let Storage = <string>localStorage.getItem(key)
        try {
            return JSON.parse(Storage)
        } catch {
            return Storage
        }
    }
}

export const isPhone = (phone: string): boolean => {
    let myreg = /^1[3-9]\d{9}$/;
    return myreg.test(phone)
}

export const format = (time: Date | number | string, fmt: string): string => {
    return moment(time).format(fmt);
}

export const isLoginAction = (): void => {
    if (!isLoginStaus()) {
        push({
            path: "/user"
        })
    }
}

export const isLoginStaus = (): boolean => {
    return getItem("token") ? true : false
}

export const firstToUpper = (str: string) => {
    console.log('str',str);
        
    return str.trim().toLowerCase().replace(str[0], str[0].toUpperCase());//
}

export const createdRouterConfig = (router: any) => {
    if (getItem("menu")) {
        getItem("menu").forEach((v: Menu) => {
            v.children.forEach(j => {
                let path = firstToUpper(v.menu_href)
                let c = {
                    path: v.menu_href + j.menu_href,
                    name: `admin_${v.menu_href}_${j.menu_href.split("/")[1]}`,
                    component: modules[`/src/views/admin/${path}${j.menu_href}.vue`],
                    meta: {
                    }
                }
                router.addRoute("admin", c)
            })
        });

        
    }
}


export const inject = () => {
    let ProxyServe: VagueOject = {}
    for (const key in serve) {
        // get_app_articleList
        // ['get','app','articleList']
        let splitArr: string[] = key.split("_");
        // 请求方法 GET  POST
        let methodsType: 'GET' | 'POST' = <'GET' | 'POST'>splitArr[0].toLocaleUpperCase()

        // 请求基地址的key
        let BaseUrlPrefix: PrefixType = <PrefixType>splitArr[1]
        let baseUrl: string = import.meta.env.MODE == "development"
            ? config.baseUrl[BaseUrlPrefix].devBaseUrl
            : config.baseUrl[BaseUrlPrefix].prodBaseUrl

        // 请求短地址的key
        let UrlShort: string = splitArr[2]
        // 是否需要处理响应结果
        let ishandle: string = splitArr[3]

        if (ishandle != undefined && ishandle != "handle") {
            throw new Error(`方法名${key}中的参数${ishandle}需要为 handle`)
        }

        ProxyServe[UrlShort] = new Proxy(serve[key], {
            apply: async (target, ctx, args) => {
                let res = await api[methodsType]<any>({
                    baseUrl,
                    url: config.apiList[BaseUrlPrefix][UrlShort],
                    data: args[0] == undefined ? {} : args[0],
                    header: args[1] == undefined ? {} : args[1]
                })
                return ishandle == undefined ? res : target(res)
            }
        })
    }
    return ProxyServe
}

export default inject()

// function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
//     return key in object;
// }
